using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Repositories;

namespace Lzfy_Refund_Service.Services
{
    /// <summary>
    /// 用户修改日志服务实现
    /// </summary>
    public class UumUserModifyLogService : IUumUserModifyLogService
    {
        private readonly IUumUserModifyLogRepository _repository;
        private readonly ILogger<UumUserModifyLogService> _logger;

        public UumUserModifyLogService(IUumUserModifyLogRepository repository, ILogger<UumUserModifyLogService> logger)
        {
            _repository = repository;
            _logger = logger;
        }

        /// <summary>
        /// 创建用户修改日志
        /// </summary>
        public async Task<long> CreateAsync(UumUserModifyLogCreateRequest request)
        {
            try
            {
                // 参数验证
                if (string.IsNullOrWhiteSpace(request.UserName))
                {
                    throw new ArgumentException("用户名不能为空", nameof(request.UserName));
                }

                if (string.IsNullOrWhiteSpace(request.ColName))
                {
                    throw new ArgumentException("修改的列名不能为空", nameof(request.ColName));
                }

                if (string.IsNullOrWhiteSpace(request.UserNameModify))
                {
                    throw new ArgumentException("修改用户名不能为空", nameof(request.UserNameModify));
                }

                var log = new UumUserModifyLog
                {
                    UserName = request.UserName.Trim(),
                    ColName = request.ColName.Trim(),
                    UserNameModify = request.UserNameModify.Trim(),
                    OriginValue = request.OriginValue?.Trim(),
                    UpdateValue = request.UpdateValue?.Trim()
                };

                var id = await _repository.CreateAsync(log);

                _logger.LogInformation("创建用户修改日志成功，ID: {Id}, 用户: {UserName}, 列名: {ColName}, 修改用户: {UserNameModify}", 
                    id, request.UserName, request.ColName, request.UserNameModify);

                return id;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建用户修改日志失败，用户: {UserName}, 列名: {ColName}", 
                    request.UserName, request.ColName);
                throw;
            }
        }

        /// <summary>
        /// 根据ID获取用户修改日志
        /// </summary>
        public async Task<UumUserModifyLog?> GetByIdAsync(long id)
        {
            try
            {
                if (id <= 0)
                {
                    throw new ArgumentException("ID必须大于0", nameof(id));
                }

                var result = await _repository.GetByIdAsync(id);

                _logger.LogInformation("查询用户修改日志，ID: {Id}, 结果: {Found}", id, result != null ? "找到" : "未找到");

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询用户修改日志失败，ID: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 分页查询用户修改日志
        /// </summary>
        public async Task<UumUserModifyLogQueryResponse> GetPagedAsync(UumUserModifyLogQueryRequest request)
        {
            try
            {
                // 参数验证
                if (request.PageIndex <= 0)
                {
                    request.PageIndex = 1;
                }

                if (request.PageSize <= 0 || request.PageSize > 100)
                {
                    request.PageSize = 20;
                }

                // 日期范围验证
                if (request.StartDate.HasValue && request.EndDate.HasValue && request.StartDate > request.EndDate)
                {
                    throw new ArgumentException("开始时间不能大于结束时间");
                }

                var (data, totalCount) = await _repository.GetPagedAsync(request);

                var response = new UumUserModifyLogQueryResponse
                {
                    Items = data.ToList(),
                    TotalCount = totalCount,
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize
                };

                _logger.LogInformation("分页查询用户修改日志，页码: {PageIndex}, 每页: {PageSize}, 总数: {TotalCount}", 
                    request.PageIndex, request.PageSize, totalCount);

                return response;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分页查询用户修改日志失败");
                throw;
            }
        }

        /// <summary>
        /// 根据用户名获取修改日志
        /// </summary>
        public async Task<IEnumerable<UumUserModifyLog>> GetByUserNameAsync(string userName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userName))
                {
                    throw new ArgumentException("用户名不能为空", nameof(userName));
                }

                var result = await _repository.GetByUserNameAsync(userName.Trim());

                _logger.LogInformation("根据用户名查询修改日志，用户: {UserName}, 记录数: {Count}", 
                    userName, result.Count());

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据用户名查询修改日志失败，用户: {UserName}", userName);
                throw;
            }
        }

        /// <summary>
        /// 根据修改用户名获取修改日志
        /// </summary>
        public async Task<IEnumerable<UumUserModifyLog>> GetByUserNameModifyAsync(string userNameModify)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userNameModify))
                {
                    throw new ArgumentException("修改用户名不能为空", nameof(userNameModify));
                }

                var result = await _repository.GetByUserNameModifyAsync(userNameModify.Trim());

                _logger.LogInformation("根据修改用户名查询修改日志，修改用户: {UserNameModify}, 记录数: {Count}", 
                    userNameModify, result.Count());

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据修改用户名查询修改日志失败，修改用户: {UserNameModify}", userNameModify);
                throw;
            }
        }

        /// <summary>
        /// 获取最近的修改日志
        /// </summary>
        public async Task<IEnumerable<UumUserModifyLog>> GetRecentAsync(int minutes = 60)
        {
            try
            {
                if (minutes <= 0)
                {
                    minutes = 60;
                }

                if (minutes > 1440) // 最多24小时
                {
                    minutes = 1440;
                }

                var result = await _repository.GetRecentAsync(minutes);

                _logger.LogInformation("查询最近修改日志，时间范围: {Minutes}分钟, 记录数: {Count}", 
                    minutes, result.Count());

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询最近修改日志失败，时间范围: {Minutes}分钟", minutes);
                throw;
            }
        }
    }
}